package net;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by Xiang on 2014/8/25.
 */
public class ThreadEchoServer {
    public static void main(String[] args) {
        try {
            int i = 1; int j = 2;
            ServerSocket s = new ServerSocket(8189);

            while(true) {
                Socket incoming = s.accept();
                System.out.println("Spawning" + i);
                Runnable r = new ThreadEchoHander(incoming);
                Thread t = new Thread(r);
                t.start();
                i++;
            }

        } catch (IOException e){

        }
    }
}

class ThreadEchoHander implements Runnable {

    private Socket incoming;

    public ThreadEchoHander(Socket i) {
        incoming = i;
    }

    @Override
    public void run() {
        try {
            try{
                InputStream inStream = incoming.getInputStream();
                OutputStream outStream = incoming.getOutputStream();
                Scanner in = new Scanner(inStream);
                PrintWriter out = new PrintWriter(outStream,true);

                boolean done = false;
                while(!done && in.hasNext()) {
                    String line = in.nextLine();
                    out.println("Echo:" + line);
                    if (line.trim().equals("BYE")) {
                        done = true;
                    }
                }
            } finally {
                incoming.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
